package chapter26;

import java.time.Instant;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/28 20:37
 */
public class CompletableFutureTest2 {
    private static final ExecutorService exec = Executors.newFixedThreadPool(10);
    private static Random random = new Random();

    public static void main(String[] args) {
        CompletableFuture<String> taskA = CompletableFuture.supplyAsync(() -> {
            delayRandom(100, 100);
            return "hello";
        }, exec);

        CompletableFuture<Void> taskB = CompletableFuture.runAsync(() -> delayRandom(2000, 3000), exec);

        CompletableFuture<Void> taskC = CompletableFuture.runAsync(() -> {
            delayRandom(30, 100);
            throw new RuntimeException("task c exception");
        }, exec);

        CompletableFuture.allOf(taskA, taskB, taskC).whenComplete((result, ex) -> {
            if (ex != null) {
                System.out.println(ex.getMessage());
            }

            if (!taskA.isCompletedExceptionally()) {
                System.out.println("task a" + taskA.join());
            }
        });
    }

    private static int delayRandom(int min, int max) {
        int milli = max > min ? random.nextInt(max - min) : 0;
        System.out.println("begin:" + Instant.now());
        try {
            TimeUnit.MILLISECONDS.sleep(milli);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("end:" + Instant.now());
        return milli;
    }

}
